//
//  StatusCellPictureView.swift
//  Weobo
//
//  Created by 史亚洲 on 16/1/19.
//  Copyright © 2016年 itcast. All rights reserved.
//
/*
根据配图视图数量,计算配图视图的大小
*/
import UIKit
import SDWebImage



private let pictureCellId = "pictureCellId"

private let pictureCellMargin: CGFloat = 5

class StatusCellPictureView: UICollectionView {
    
    
    var imageURLs: [NSURL]? {
        didSet {
        
            //计算配图视图大小
            let pSize=caclePictureViewSize()
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            testLabel.text="\(imageURLs?.count ?? 0)"
            
            //更改数据源后,一定要刷新数据
            reloadData()
        
        
        }
    
    
    }
    /*
    1.单图:按照图片等比例显示
    2.多图的大小固定
    四张图:会按照2 * 2显示
    九张图:3 * 3显示

    */
    
    private func caclePictureViewSize() ->CGSize {
        let imageCount = imageURLs?.count ?? 0
        
        //1.没有配图
        if imageCount == 0 {
        
        return CGSizeZero
        }
        //获取集合视图的布局现象
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //2.一张配图
        if imageCount == 1 {
            //等比例显示图片,去缓存中获取图片
            let key=imageURLs?.first?.absoluteString ?? ""
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            let itemSize=image.size
            
            layout.itemSize=image.size
            
            return itemSize
        
        }
        
        //大于两张图时,配图的宽高都是相同的
        let itemWidth=(KWidth-StatusCellMargin*2-pictureCellMargin*2)/3
        
        //设置多张图片的itemSize
         layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        if imageCount == 4 {
        
        //按照2*2显示
            let w=itemWidth*2+pictureCellMargin
            return CGSizeMake(w, w)

        }
        //程序走到这里  2, 3, 5,6,7,8,9
        /*
        1,2,3   ==> 1
        4,5,6   ==> 2
        7,8,9   ==> 3
        */
        //1.确定行数
        let row = CGFloat((imageCount-1)/3+1)
        
        //2.计算最大宽度
        let maxW=itemWidth*3+2*pictureCellMargin
        let maxH=itemWidth*row+(row-1)*pictureCellMargin
        return CGSizeMake(maxW, maxH)

    }
    
    
    //找到自定义入口
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        
        //设置间距
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        self.backgroundColor=UIColor.whiteColor()
        setupUI()
       
        
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    private func setupUI() {
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
        
        //注册cell
        registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellId)
        
        //设置数据源代理
        self.dataSource=self
        
        //设置代理
        self.delegate=self
        
        //禁用快速回到顶部的属性
        self.scrollsToTop=false
    
    
    }
    
    //MARK:懒加载子视图
    private lazy var testLabel: UILabel = UILabel(title: "", fontSize: 40, color: UIColor.redColor())

}
extension StatusCellPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    //实现必须实现的数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellId, forIndexPath: indexPath) as! PictureCell
        
        cell.imageURL=imageURLs![indexPath.item]
        //indexPath.item%2取奇偶数
        //cell.backgroundColor = indexPath.item%2 == 0 ? UIColor.purpleColor() : UIColor.redColor()
        return cell
    }
    
    //点击cell,看大图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //1.创建SDPhotoBrowser实例
        let brower=SDPhotoBrowser()
        //2.原图的父控件
        brower.sourceImagesContainerView=self
        //3.原图的数量;
        brower.imageCount=imageURLs?.count ?? 0
        //4. 当前需要展示图片的index
        brower.currentImageIndex=indexPath.item
        brower.delegate=self
        //5. 展示图片浏览器
        brower.show()
    }
    

}
extension StatusCellPictureView: SDPhotoBrowserDelegate{
    
    //返回高质量的图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //1.获取图片的url
        let url=imageURLs![index]
        
        //2.将url转换为字符串
        let urlString=url.absoluteString
        
        //3.字符串的替换
        let largeUrlString=urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
        
        let largeUrl=NSURL(string: largeUrlString)
        return largeUrl
    }
    //返回展位图对应的图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        if let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as? PictureCell {
            return cell.iconView.image

        }
        
        return nil
    }
    
    
    
}

//在同一个 "文件" 中声明另外一个类
class PictureCell: UICollectionViewCell {
    
    //MARK:定义外部变量
    var imageURL: NSURL? {
    
        didSet {
        
            //设置url
            iconView.sd_setImageWithURL(imageURL)
            print(imageURL?.absoluteString)
        
        
        }
    
    
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

//设置视图
    private func setupUI() {
    
    contentView.addSubview(iconView)
    iconView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(contentView.snp_edges)
        }
    
    }


//懒加载子视图
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        //视图内容显示模式 默认显示 是 ContentModeScaleToFill   ==> 缩放进行填充  比例一致的图片使用这种样式显示
        //.ScaleAspectFit 图片显示上下可能会留白  基本不会使用这样显示样式
        //ScaleAspectFill 视图会被剪裁  但是 图片显示不会失真  并且不会留白
        iv.contentMode = .ScaleAspectFill
        //手写代码 不会自动设置剪裁
        iv.clipsToBounds = true
        return iv
    }()


}


